//
//  MPVideoViewController_iPad.m
//  MissPaparazzi
//
//  Created by Alexey Aleshkov on 18.08.12.
//  Copyright (c) 2012 DzeTech. All rights reserved.
//


#import "MPVideoViewController.h"
#import "FXLabel.h"
#import "FXLabel+MPNavigationBarTitle.h"
#import "UIGlossyButton.h"
#import "UIGlossyButton+MPNavigationBarTitle.h"
#import "MPStore.h"
#import "UIWebView+InnerShadow.h"
#import "MPAppDelegate.h"


@interface MPVideoViewController ()

@end


@implementation MPVideoViewController

@synthesize data = _data;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
	}
	return self;
}

- (void)dealloc
{
	[_moviePlayer.view removeFromSuperview];
	[_moviePlayer release];
	[_moviePlayerSuperView release];
	[_descriptionWebView release];
	[_indicatorView release];
	[_data release];
	[_holePatternView release];
	[_shadowView release];
	[_videoViewContent release];
	[super dealloc];
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	
	NSString *titleViewLabelTitle = _data.name;
	FXLabel *titleViewLabel = [[FXLabel alloc] init];
	[titleViewLabel setMPNavigationBarTitleStyle];
	titleViewLabel.text = titleViewLabelTitle;
	titleViewLabel.font = [UIFont boldSystemFontOfSize:16];
	titleViewLabel.numberOfLines = 2;
	titleViewLabel.adjustsFontSizeToFitWidth = YES;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		titleViewLabel.frame = CGRectMake(0, 0, 180, 44);
	} else {
		if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
			titleViewLabel.frame = CGRectMake(0, 0, 840, 44);
		} else {
			titleViewLabel.frame = CGRectMake(0, 0, 640, 44);
		}
	}
	titleViewLabel.autoresizingMask = (UIViewAutoresizingFlexibleWidth);
	self.navigationItem.titleView = titleViewLabel;
	[titleViewLabel release];
	
	NSString *leftBarBackButtonTitle = NSLocalizedString(@"NavigationBar.BackButton.Title", @"");
	UIGNavigationButton *leftBarBackButton = [[UIGNavigationButton alloc] initWithFrame:CGRectMake(0, 0, 60, 32)];
	[leftBarBackButton addTarget:self action:@selector(backButtonTouchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
	[leftBarBackButton setTitle:leftBarBackButtonTitle forState:UIControlStateNormal];
	leftBarBackButton.leftArrow = YES;
	[leftBarBackButton setMPNavigationBarTitleStyle];
	UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarBackButton];
	self.navigationItem.leftBarButtonItem = leftBarButtonItem;
	[leftBarButtonItem release];
	[leftBarBackButton release];
	
	_holePatternView.patternImage = [UIImage imageNamed:@"Pattern"];
	_holePatternView.fillColor = [UIColor colorWithWhite:0 alpha:0.16];
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		_holePatternView.holeInsets = UIEdgeInsetsMake(204, 5, 4, 5);
	} else {
		_holePatternView.holeInsets = UIEdgeInsetsMake(600, 16, 8, 16);
	}
	_holePatternView.holeRadius = 6;
	_shadowView.shadowBlur = 12;
	_shadowView.shadowRadius = _holePatternView.holeRadius;
	_shadowView.shadowInsets = _holePatternView.holeInsets;

	_descriptionWebView.innerShadowHidden = YES;
	static NSString *htmlFormat =
	@"<html>"
	@"<head>"
	@"<style type=\"text/css\">"
	@"li {color: white;}"
	@"a {color: white;}"
	@"</style>"
	@"</head>"
	@"<body link=\"#000000\" style=\"background-color:transparent; font-family:Helvetica; padding: 6; margin: 0; color:white;\">"
	@"<span font-size:14px\">%@</span><br/><br/>"
	@"</body>"
	@"</html>";
	NSString *html = [NSString stringWithFormat:htmlFormat, _data.fullText];
	[_descriptionWebView loadHTMLString:html baseURL:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerWillExitFullscreen:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerDidEnterFullScreen:) name:MPMoviePlayerDidEnterFullscreenNotification object:nil];
	
	_moviePlayer = [[MPMoviePlayerController alloc] init];
	_moviePlayer.view.backgroundColor = [UIColor clearColor];
	_moviePlayer.view.frame = CGRectMake(0, 0, _moviePlayerSuperView.frame.size.width, _moviePlayerSuperView.frame.size.height);
	_moviePlayer.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
	[_moviePlayer prepareToPlay];
	_moviePlayer.repeatMode = MPMovieRepeatModeNone;
	_moviePlayer.shouldAutoplay = NO;
	_moviePlayer.movieSourceType = MPMovieSourceTypeFile;
	[_moviePlayerSuperView addSubview:_moviePlayer.view];
	
	NSString *contentPathString = [[MPStore sharedInstance] videoPathForItem:_data];
	NSURL *contentURL = [NSURL fileURLWithPath:contentPathString];
	_moviePlayer.contentURL = contentURL;
	
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
		[NSThread sleepForTimeInterval:1.0];
		dispatch_async(dispatch_get_main_queue(), ^(void) {
			[_moviePlayer prepareToPlay];
			_moviePlayer.shouldAutoplay = YES;
			[_moviePlayer play];
		});
	});
}

- (void)viewDidUnload
{
	[_moviePlayerSuperView release];
	_moviePlayerSuperView = nil;
	[_descriptionWebView release];
	_descriptionWebView = nil;
	[_indicatorView release];
	_indicatorView = nil;
	[_holePatternView release];
	_holePatternView = nil;
	[_shadowView release];
	_shadowView = nil;
	[_videoViewContent release];
	_videoViewContent = nil;
	[super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	[self willRotateToInterfaceOrientation:self.interfaceOrientation duration:0];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	BOOL result;
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		result = (UIInterfaceOrientationPortrait == interfaceOrientation);
	} else {
		result = YES;
	}

	return result;
}

- (BOOL)shouldAutorotate
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		return NO;
	} else {
		return YES;
	}
}

- (NSUInteger)supportedInterfaceOrientations
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
		return UIInterfaceOrientationMaskPortrait;
	} else {
		return UIInterfaceOrientationMaskAll;
	}
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
	} else {
		CGRect landscapeFrame = CGRectMake(18, 6, 988, 588);
		CGFloat ratio = landscapeFrame.size.width / landscapeFrame.size.height;
		CGRect frame;
		UIEdgeInsets shadowInsets;
		CGRect webViewFrame;
		if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
			frame = landscapeFrame;
			shadowInsets = UIEdgeInsetsMake(600, 16, 8, 16);
			webViewFrame = CGRectMake(18, 600, 988, 96);
		} else {
			frame = landscapeFrame;
			frame.size.width = 768 - (landscapeFrame.origin.x * 2);
			frame.size.height = frame.size.width / ratio;
			shadowInsets = UIEdgeInsetsMake(450, 16, 8, 16);
			webViewFrame = CGRectMake(18, 450, 988, 502);
		}
		_videoViewContent.frame = frame;

		_holePatternView.holeInsets = shadowInsets;
		_shadowView.shadowInsets = _holePatternView.holeInsets;
		
		_descriptionWebView.frame = webViewFrame;
	}
}

// In iOS 4.3 - 5.1 this methods not called
// In iOS 6 this methods called
//- (void)viewWillDisappear:(BOOL)animated

- (void)moviePlayerDidEnterFullScreen:(NSNotification *)notification
{
	NSArray *versionCompatibility = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
	if ([[versionCompatibility objectAtIndex:0] integerValue] < 6) {
		[self.navigationController setNavigationBarHidden:YES animated:YES];
	}
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kMPIsFullScreenVideoPlayer];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)moviePlayerWillExitFullscreen:(NSNotification *)notification
{
	[self willRotateToInterfaceOrientation:self.interfaceOrientation duration:0];

	NSArray *versionCompatibility = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
	if ([[versionCompatibility objectAtIndex:0] integerValue] < 6) {
		[self.navigationController setNavigationBarHidden:NO animated:NO];
		[self.navigationController popViewControllerAnimated:NO];
	}
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kMPIsFullScreenVideoPlayer];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark -
#pragma mark Actions

- (IBAction)backButtonTouchUpInsideAction:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}

@end
